﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ExternalConnections.CApECExcelExportManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.ExternalConnections.Res;
using EngineeringInternalExtension;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace DnProcessSimulateCommands.ExternalConnections;

internal class CApECExcelExportManager : CApECExcelManager
{
  private CApECExcelExportParams m_params;
  private Dictionary<CApECGeneralUtils.eColumnDataType, int> m_columnTypeToExcelColIndexMap;

  internal CApECExcelExportManager()
  {
  }

  internal bool Export(CApECExcelExportParams exportParams, string forceExportPath)
  {
    bool flag1 = forceExportPath != null;
    bool flag2 = false;
    if (this.Start())
    {
      this.m_params = exportParams;
      try
      {
        CApECExcelExportManager.FileSaveInfo info = (CApECExcelExportManager.FileSaveInfo) null;
        bool flag3 = true;
        if (flag1)
        {
          flag2 = this.ShowSaveAsDialog(this.m_params.DefaultFileName, forceExportPath, out info);
          flag3 = flag2 && info.SaveConfirmed;
        }
        if (flag3)
        {
          this.m_excelApp.Visible = false;
          this.m_excelApp.DisplayAlerts = false;
          flag2 = this.CreateWorkbookAndSheet();
          if (flag2)
            flag2 = this.ExportToSheet();
          this.m_excelApp.Visible = !flag1;
        }
        if (flag2 & flag1)
          flag2 = this.SaveWorkbook(info);
      }
      catch (COMException ex)
      {
        int errorCode = ex.ErrorCode;
        flag2 = false;
      }
      finally
      {
        if (flag1)
          this.Quit();
        else
          this.Release();
      }
    }
    return flag2;
  }

  private bool CreateWorkbookAndSheet()
  {
    bool workbookAndSheet = false;
    if (this.m_excelApp != null)
    {
      // ISSUE: reference to a compiler-generated method
      this.m_workbook = this.m_excelApp.Workbooks.Add((object) Missing.Value);
      if (this.m_workbook != null)
      {
        this.m_sheet = this.m_workbook.Sheets[(object) 1] as Worksheet;
        if (this.m_sheet != null)
        {
          this.m_sheet.Name = CUiECExternalConnectionsResourceTable.EXPORT_EXCEL_SHEET_NAME;
          workbookAndSheet = true;
        }
      }
    }
    return workbookAndSheet;
  }

  private bool SaveWorkbook(CApECExcelExportManager.FileSaveInfo saveInfo)
  {
    bool flag = false;
    if (this.m_excelApp != null && this.m_workbook != null)
    {
      if (saveInfo.UseDefaultFormat)
      {
        // ISSUE: reference to a compiler-generated method
        this.m_workbook._SaveAs((object) saveInfo.FilePath, (object) Missing.Value, (object) Missing.Value, (object) Missing.Value, (object) Missing.Value, (object) Missing.Value, ConflictResolution: (object) Missing.Value, AddToMru: (object) Missing.Value, TextCodepage: (object) Missing.Value, TextVisualLayout: (object) Missing.Value);
      }
      else
      {
        // ISSUE: reference to a compiler-generated method
        this.m_workbook._SaveAs((object) saveInfo.FilePath, (object) saveInfo.UseXlFormat, (object) Missing.Value, (object) Missing.Value, (object) Missing.Value, (object) Missing.Value, ConflictResolution: (object) Missing.Value, AddToMru: (object) Missing.Value, TextCodepage: (object) Missing.Value, TextVisualLayout: (object) Missing.Value);
      }
      flag = true;
    }
    return flag;
  }

  private bool ShowSaveAsDialog(
    string defaultFileName,
    string forceExportPath,
    out CApECExcelExportManager.FileSaveInfo info)
  {
    bool flag1 = false;
    info = (CApECExcelExportManager.FileSaveInfo) null;
    if (this.m_excelApp != null)
    {
      int firstPositiveInt = this.ExtractFirstPositiveInt(this.m_excelApp.Version);
      bool flag2 = false;
      string empty = string.Empty;
      string str;
      if (firstPositiveInt >= 12)
      {
        str = "Microsoft Excel Workbook (*.xls;*.xlsx)|*.xls;*.xlsx";
        flag2 = true;
      }
      else
        str = "Microsoft Excel Workbook (*.xls)|*.xls";
      SaveFileDialog saveFileDialog = new SaveFileDialog();
      saveFileDialog.Title = this.m_params.BrowseDialogTitle;
      saveFileDialog.CheckPathExists = true;
      saveFileDialog.DefaultExt = "xls";
      saveFileDialog.FileName = defaultFileName;
      saveFileDialog.Filter = str;
      saveFileDialog.OverwritePrompt = true;
      saveFileDialog.AddExtension = true;
      flag1 = true;
      info = new CApECExcelExportManager.FileSaveInfo();
      info.SaveConfirmed = forceExportPath != null || saveFileDialog.ShowDialog() == DialogResult.OK;
      if (info.SaveConfirmed)
      {
        info.FilePath = forceExportPath == null ? saveFileDialog.FileName : forceExportPath;
        info.UseDefaultFormat = false;
        info.UseXlFormat = XlFileFormat.xlWorkbookNormal;
        string lower = info.FilePath.ToLower();
        if (lower.EndsWith(".xlsx"))
          info.UseDefaultFormat = true;
        else if (lower.EndsWith(".xls") && flag2)
          info.UseXlFormat = XlFileFormat.xlAddIn;
      }
    }
    return flag1;
  }

  private bool ExportToSheet()
  {
    object[,] values = new object[this.m_params.DataListToExport.Count + 1, this.m_params.ColumnTypeToColDataMap.Count];
    bool sheet = this.ProcessHeaders(values);
    if (sheet)
      sheet = this.ExportAllData(values);
    if (sheet)
      sheet = this.FinalizeExport(values);
    return sheet;
  }

  private bool ProcessHeaders(object[,] values)
  {
    bool flag = true;
    this.m_columnTypeToExcelColIndexMap = new Dictionary<CApECGeneralUtils.eColumnDataType, int>(this.m_params.ColumnTypeToColDataMap.Count);
    Dictionary<CApECGeneralUtils.eColumnDataType, CApECExcelBaseParams.ColData>.Enumerator enumerator = this.m_params.ColumnTypeToColDataMap.GetEnumerator();
    int row = 0;
    int column = 0;
    while (enumerator.MoveNext())
    {
      flag = this.SetCellValue(values, row, column, (object) enumerator.Current.Value.Caption);
      if (flag)
      {
        this.m_columnTypeToExcelColIndexMap.Add(enumerator.Current.Key, column);
        ++column;
      }
      else
        break;
    }
    return flag;
  }

  private bool ExportAllData(object[,] values)
  {
    bool flag = true;
    int row = 0 + 1;
    foreach (ITxPlcExternalConnectionDataEx data in this.m_params.DataListToExport)
    {
      flag = this.ExportData(values, data, row);
      if (flag)
        ++row;
      else
        break;
    }
    return flag;
  }

  private bool ExportData(object[,] values, ITxPlcExternalConnectionDataEx data, int row)
  {
    bool flag = true;
    Dictionary<CApECGeneralUtils.eColumnDataType, int>.Enumerator enumerator = this.m_columnTypeToExcelColIndexMap.GetEnumerator();
    this.m_params.DataConvertor = (IApECExternalConnectionDataConvertor) new CApECExternalConnectionDataExportConvertor(data);
    IApECExternalConnectionDataConvertor instance = this.m_params.DataConvertor.CreateInstance(data);
    while (enumerator.MoveNext())
    {
      int column = enumerator.Current.Value;
      object obj = (object) null;
      switch (enumerator.Current.Key)
      {
        case CApECGeneralUtils.eColumnDataType.Name:
          obj = instance.Name;
          break;
        case CApECGeneralUtils.eColumnDataType.Type:
          obj = instance.Type;
          break;
        case CApECGeneralUtils.eColumnDataType.OpcServer:
          obj = instance.OpcServer;
          break;
        case CApECGeneralUtils.eColumnDataType.ItemHeader:
          obj = instance.ItemHeader;
          break;
        case CApECGeneralUtils.eColumnDataType.NameSpaceIndex:
          obj = instance.NameSpaceIndex;
          break;
        case CApECGeneralUtils.eColumnDataType.InstanceName:
          obj = instance.InstanceName;
          break;
        case CApECGeneralUtils.eColumnDataType.COMElement:
          obj = instance.COMElement;
          break;
        case CApECGeneralUtils.eColumnDataType.MapSignalsBy:
          obj = instance.MapSignalsBy;
          break;
        case CApECGeneralUtils.eColumnDataType.PluginState:
          obj = instance.PluginState;
          break;
        case CApECGeneralUtils.eColumnDataType.TagAccessMode:
          obj = instance.TagAccessMode;
          break;
      }
      flag = obj != null && this.SetCellValue(values, row, column, obj);
    }
    return flag;
  }

  private bool FinalizeExport(object[,] values)
  {
    bool flag = false;
    if (this.m_sheet != null)
    {
      // ISSUE: variable of a compiler-generated type
      Range range1 = this.GetRange(1, 1, values.GetLength(0), values.GetLength(1));
      if (range1 != null)
      {
        range1.EntireColumn.NumberFormat = (object) "@";
        // ISSUE: reference to a compiler-generated method
        range1.set_Value(Type.Missing, (object) values);
        Marshal.ReleaseComObject((object) range1);
        flag = true;
      }
      if (flag)
      {
        // ISSUE: variable of a compiler-generated type
        Range range2 = this.GetRange(1, 1, 1, this.m_params.ColumnTypeToColDataMap.Count);
        if (range2 != null)
        {
          range2.Font.Bold = (object) true;
          range2.HorizontalAlignment = (object) XlHAlign.xlHAlignLeft;
          range2.VerticalAlignment = (object) XlVAlign.xlVAlignCenter;
          // ISSUE: reference to a compiler-generated method
          range2.EntireColumn.AutoFit();
          range2.EntireColumn.NumberFormat = (object) "@";
          Marshal.ReleaseComObject((object) range2);
          flag = true;
        }
        else
          flag = false;
      }
    }
    return flag;
  }

  private class FileSaveInfo
  {
    internal bool SaveConfirmed;
    internal bool UseDefaultFormat;
    internal XlFileFormat UseXlFormat = XlFileFormat.xlWorkbookNormal;
    internal string FilePath = string.Empty;
  }
}
